
--[[
	**********************
	* SvFrame - thomasfn *
	**********************
	SvSpawn.lua - A plugin that adds spawn and home functionality
]]

dofile( "lua/SvFrame/plugin_header.lua" )

PLUGIN.Name = "spawn"
PLUGIN.Title = "SvSpawn"
PLUGIN.Author = "thomasfn"
PLUGIN.Folder = "SvSpawn"

function PLUGIN:Init()
	svr.AddFlag( "cansetspawn" )
	svr.AddFlag( "cansethome" )

	self:Command( "spawn", self.Spawn )
	self:Command( "setspawn", self.SetSpawn, { FLAG_CANSETSPAWN } )
	
	self:Command( "home", self.Home )
	self:Command( "sethome", self.SetHome, { FLAG_CANSETHOME } )
	
	self:Hook( "player.respawn", self.Spawn )
	self:Hook( "player.connect", self.PlayerConnect )
end

function PLUGIN:PlayerConnect( ply )
	if (ply:GetPDataN( "NotFirstTime" ) ~= 1) then
		self:Spawn( ply, {} )
		ply:SetPData( "NotFirstTime", 1 )
	end
end

function PLUGIN:Spawn( ply, args )
	if (svr.Config:GetNumber( "SpawnSet" ) ~= 1) then
		ply:ChatPrint( COL_RED, "No spawnpoint is set for this world!" )
		return
	end
	local x = svr.Config:GetNumber( "SpawnX" )
	local y = svr.Config:GetNumber( "SpawnY" )
	local z = svr.Config:GetNumber( "SpawnZ" )
	
	ply.SetPosition( Vector( x + 0.5, y, z + 0.5 ) )
end

function PLUGIN:SetSpawn( ply, args )
	local pos = ply.GetPosition()
	svr.Config:SetNumber( "SpawnX", math.floor( pos.X ) )
	svr.Config:SetNumber( "SpawnY", math.floor( pos.Y  ) )
	svr.Config:SetNumber( "SpawnZ", math.floor( pos.Z  ) )
	svr.Config:SetNumber( "SpawnSet", 1 )
	ply:ChatPrint( COL_GREEN, "Spawn position set." )
end

function PLUGIN:Home( ply, args )
	if (ply.GetPDataN( ply, "HomeSet" ) ~= 1) then
		ply:ChatPrint( COL_RED, "You haven't set your home!" )
		return
	end
	local x = ply:GetPDataN( "HomeX" )
	local y = ply:GetPDataN( "HomeY" )
	local z = ply:GetPDataN( "HomeZ" )
	ply.SetPosition( Vector( x + 0.5, y, z + 0.5 ) )
end

function PLUGIN:SetHome( ply, args )
	local pos = ply.GetPosition()
	ply:SetPData( "HomeX", math.floor( pos.X ) )
	ply:SetPData( "HomeY", math.floor( pos.Y ) )
	ply:SetPData( "HomeZ", math.floor( pos.Z ) )
	ply:SetPData( "HomeSet", 1 )
	ply:ChatPrint( COL_GREEN, "Home position set." )
end

PLUGIN:FinishLoad()